<?php

/*

	Copyright © 2011 Mike Bennett <mike@kereru.com>

	This file is part of Tazu-Time.

    Tazu-Time is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    Tazu-Time is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tazu-Time.  If not, see <http://www.gnu.org/licenses/>.
    
*/


/*
Generic config file handling 
*/

class conf {

	public $ini = array();								// ini file contents as assoc array

	protected $inifile = 'config.ini';

	function __construct($filename = 'config.ini') {

		$this->inifile = $filename;	
		$this->check_ini();
		$this->load_ini();
	
	}
	
	
	function check_ini() {
		// Can be overridden to for defaults etc.
		if ( ! file_exists($this->inifile) ) {
			file_put_contents($this->inifile,'');
		}		
	}

	function load_ini() {

		// --- INI Read and parse the ini file
		$this->check_ini();	// ini exists
		if ( file_exists($this->inifile) ) {
			$this->ini = parse_ini_file($this->inifile,TRUE);					// Load current ini
		}
		else {
			$this->ini = array();
		}

	
	}


	// write array to inifile ( backward compatibility with in class )
	function write($ini_arr) {
		$this->ini = $ini_arr;
		$initext = $this->generate_ini($ini_arr);
		file_put_contents($this->inifile, $initext); 
	}
	

	// write array to inifile
	function save_ini() {
		$initext = $this->generate_ini($this->ini);
		file_put_contents($this->inifile, $initext); 
	}


	function set_value($section,$var,$val) {
		$this->ini[$section][$var] = $val;
	}

	function generate_ini($data, $comments="") {
		
		if(!is_array($data)) {
			trigger_error(__FUNCTION__ . ": Cannot save INI file.");
			return null;
		}
	
		$text = $comments;
		while (list($name, $section) = each($data)) {
			$text .= "\r\n[$name]\r\n";
	
			while (list($key, $value) = each($section)) {


				if(is_bool($value)) {
					$value = $value?'1':'0';	// Empty string
				}
				else {
					$value = trim($value);

					if((string)((int)$value) == (string)$value)
						;	// Integer: does nothing
					elseif((string)((float)$value) == (string)$value)
						;	// Floating point: does nothing
					elseif($value === "")
						$value = '""';	// Empty string
					elseif($value[0] == '"' && $value[strlen($value)-1] == '"')
						;	// Has quotes already: does nothing
					else
						$value = '"' . $value . '"';
				}
				$text .= "$key = " . $value . "\r\n";
			}
		}
		return $text;

	}


}

?>